import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../providers/wallet_provider.dart';
import '../constants/wallet_constants.dart';
import '../widgets/network_selector_bottom_sheet.dart';

/// 导入钱包页面
class ImportWalletPage extends StatefulWidget {
  const ImportWalletPage({Key? key}) : super(key: key);

  @override
  State<ImportWalletPage> createState() => _ImportWalletPageState();
}

class _ImportWalletPageState extends State<ImportWalletPage> with TickerProviderStateMixin {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _mnemonicController = TextEditingController();
  final _privateKeyController = TextEditingController();
  
  String _selectedNetwork = 'ethereum';
  int _selectedTab = 0;
  late TabController _tabController;
  bool _isImporting = false;

  @override
  void initState() {
    super.initState();
    print('🔄 导入钱包页面初始化 - 清理旧数据');
    _tabController = TabController(length: 2, vsync: this);
    // 重置所有表单数据
    _resetFormData();
  }

  /// 重置表单数据
  void _resetFormData() {
    _nameController.clear();
    _mnemonicController.clear();
    _privateKeyController.clear();
    _selectedNetwork = 'ethereum';
    _selectedTab = 0;
    _isImporting = false;
    print('✅ 导入钱包表单已重置');
  }

  @override
  void dispose() {
    print('🗑️ 导入钱包页面销毁 - 清理资源');
    _nameController.dispose();
    _mnemonicController.dispose();
    _privateKeyController.dispose();
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF0A0E27),
      appBar: AppBar(
        title: const Text(
          '导入钱包',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: const Color(0xFF0A0E27),
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
        bottom: TabBar(
          controller: _tabController,
          onTap: (index) {
            setState(() {
              _selectedTab = index;
            });
          },
          indicatorColor: const Color(0xFF6C5CE7),
          labelColor: const Color(0xFF6C5CE7),
          unselectedLabelColor: Colors.white70,
          tabs: const [
            Tab(text: '助记词'),
            Tab(text: '私钥'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildMnemonicImport(),
          _buildPrivateKeyImport(),
        ],
      ),
    );
  }

  /// 构建助记词导入
  Widget _buildMnemonicImport() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题
            const Text(
              '通过助记词导入钱包',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              '请输入12或24个助记词，用空格分隔',
              style: TextStyle(
                fontSize: 16,
                color: Colors.white70,
              ),
            ),
            const SizedBox(height: 32),

            // 钱包名称
            _buildInputField(
              label: '钱包名称',
              controller: _nameController,
              hintText: '请输入钱包名称',
              validator: (value) {
                if (value == null || value.trim().isEmpty) {
                  return '请输入钱包名称';
                }
                if (value.trim().length < 2) {
                  return '钱包名称至少2个字符';
                }
                return null;
              },
            ),

            const SizedBox(height: 24),

            // 网络选择
            _buildNetworkSelector(),

            const SizedBox(height: 24),

            // 助记词输入
            _buildMnemonicInput(),

            const SizedBox(height: 32),

            // 导入按钮
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: _isImporting ? null : _importFromMnemonic,
                icon: _isImporting
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : const Icon(Icons.download),
                label: Text(_isImporting ? '导入中...' : '导入钱包'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF6C5CE7),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建私钥导入
  Widget _buildPrivateKeyImport() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题
            const Text(
              '通过私钥导入钱包',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              '请输入64位十六进制私钥',
              style: TextStyle(
                fontSize: 16,
                color: Colors.white70,
              ),
            ),
            const SizedBox(height: 32),

            // 钱包名称
            _buildInputField(
              label: '钱包名称',
              controller: _nameController,
              hintText: '请输入钱包名称',
              validator: (value) {
                if (value == null || value.trim().isEmpty) {
                  return '请输入钱包名称';
                }
                if (value.trim().length < 2) {
                  return '钱包名称至少2个字符';
                }
                return null;
              },
            ),

            const SizedBox(height: 24),

            // 网络选择
            _buildNetworkSelector(),

            const SizedBox(height: 24),

            // 私钥输入
            _buildPrivateKeyInput(),

            const SizedBox(height: 32),

            // 导入按钮
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                onPressed: _isImporting ? null : _importFromPrivateKey,
                icon: _isImporting
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : const Icon(Icons.download),
                label: Text(_isImporting ? '导入中...' : '导入钱包'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF6C5CE7),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建输入框
  Widget _buildInputField({
    required String label,
    required TextEditingController controller,
    String? hintText,
    String? Function(String?)? validator,
    bool obscureText = false,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: Colors.white,
          ),
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: controller,
          validator: validator,
          obscureText: obscureText,
          autovalidateMode: AutovalidateMode.onUserInteraction, // 添加自动验证模式
          style: const TextStyle(color: Colors.white),
          decoration: InputDecoration(
            hintText: hintText,
            hintStyle: const TextStyle(color: Colors.white54),
            filled: true,
            fillColor: const Color(0xFF1E2139),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide(color: Colors.white.withOpacity(0.1)),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: Color(0xFF6C5CE7)),
            ),
            focusedErrorBorder: OutlineInputBorder( // 添加聚焦错误状态边框
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: Colors.red, width: 2),
            ),
            errorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: Colors.red),
            ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 16,
            ),
          ),
        ),
      ],
    );
  }

  /// 构建网络选择器
  Widget _buildNetworkSelector() {
    final selectedNetwork = WalletConstants.supportedNetworks[_selectedNetwork];
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '选择网络',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: Colors.white,
          ),
        ),
        const SizedBox(height: 8),
        Material(
          color: const Color(0xFF1E2139),
          borderRadius: BorderRadius.circular(12),
          child: InkWell(
            onTap: _showNetworkBottomSheet,
            borderRadius: BorderRadius.circular(12),
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: Colors.white.withOpacity(0.1)),
              ),
              child: Row(
                children: [
                  Container(
                    width: 8,
                    height: 8,
                    decoration: const BoxDecoration(
                      color: Color(0xFF6C5CE7),
                      shape: BoxShape.circle,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      selectedNetwork?.name ?? 'Unknown',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                      ),
                    ),
                  ),
                  const Icon(
                    Icons.arrow_drop_down,
                    color: Colors.white70,
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 显示网络选择底部弹出框
  Future<void> _showNetworkBottomSheet() async {
    final selectedNetwork = await NetworkSelectorBottomSheet.show(
      context,
      currentNetwork: _selectedNetwork,
    );
    
    if (selectedNetwork != null) {
      setState(() {
        _selectedNetwork = selectedNetwork;
      });
    }
  }

  /// 构建助记词输入
  Widget _buildMnemonicInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '助记词',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: Colors.white,
          ),
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: _mnemonicController,
          maxLines: 4,
          style: const TextStyle(color: Colors.white),
          decoration: InputDecoration(
            hintText: '请输入12或24个助记词，用空格分隔\n例如: abandon abandon abandon...',
            hintStyle: const TextStyle(color: Colors.white54),
            filled: true,
            fillColor: const Color(0xFF1E2139),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide(color: Colors.white.withOpacity(0.1)),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: Color(0xFF6C5CE7)),
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
          validator: (value) {
            if (value == null || value.trim().isEmpty) {
              return '请输入助记词';
            }
            final words = value.trim().split(RegExp(r'\s+'));
            if (words.length != 12 && words.length != 24) {
              return '助记词必须是12个或24个单词';
            }
            return null;
          },
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            IconButton(
              onPressed: _pasteMnemonic,
              icon: const Icon(Icons.paste, color: Color(0xFF6C5CE7)),
              tooltip: '粘贴助记词',
            ),
            const Text(
              '从剪贴板粘贴',
              style: TextStyle(color: Colors.white70),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建私钥输入
  Widget _buildPrivateKeyInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '私钥',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: Colors.white,
          ),
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: _privateKeyController,
          maxLines: 3,
          style: const TextStyle(color: Colors.white),
          decoration: InputDecoration(
            hintText: '请输入64位十六进制私钥\n例如: 0x1234...',
            hintStyle: const TextStyle(color: Colors.white54),
            filled: true,
            fillColor: const Color(0xFF1E2139),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide(color: Colors.white.withOpacity(0.1)),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: const BorderSide(color: Color(0xFF6C5CE7)),
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
          validator: (value) {
            if (value == null || value.trim().isEmpty) {
              return '请输入私钥';
            }
            final privateKey = value.trim();
            if (!privateKey.startsWith('0x') || privateKey.length != 66) {
              return '私钥格式不正确，应为0x开头的66位十六进制';
            }
            return null;
          },
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            IconButton(
              onPressed: _pastePrivateKey,
              icon: const Icon(Icons.paste, color: Color(0xFF6C5CE7)),
              tooltip: '粘贴私钥',
            ),
            const Text(
              '从剪贴板粘贴',
              style: TextStyle(color: Colors.white70),
            ),
          ],
        ),
        const SizedBox(height: 16),
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.red.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.red.withOpacity(0.3)),
          ),
          child: Row(
            children: [
              const Icon(Icons.warning, color: Colors.red),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '安全警告',
                      style: TextStyle(
                        color: Colors.red,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    const Text(
                      '私钥是钱包的核心，请确保在安全的环境下输入，不要泄露给他人。',
                      style: TextStyle(
                        color: Colors.white70,
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 粘贴助记词
  void _pasteMnemonic() async {
    final data = await Clipboard.getData(Clipboard.kTextPlain);
    if (data?.text != null) {
      _mnemonicController.text = data!.text!;
    }
  }

  /// 粘贴私钥
  void _pastePrivateKey() async {
    final data = await Clipboard.getData(Clipboard.kTextPlain);
    if (data?.text != null) {
      _privateKeyController.text = data!.text!;
    }
  }

  /// 从助记词导入
  Future<void> _importFromMnemonic() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      setState(() {
        _isImporting = true;
      });

      // 导入钱包，不立即加载余额
      await context.read<WalletProvider>().importWallet(
        name: _nameController.text.trim(),
        networkId: _selectedNetwork,
        mnemonic: _mnemonicController.text.trim(),
        loadDataImmediately: false, // 加快导入速度
      );

      if (mounted) {
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('✅ 钱包导入成功'),
            backgroundColor: Colors.green,
          ),
        );
        
        // 返回主页后，异步加载钱包数据
        Future.delayed(const Duration(milliseconds: 300), () {
          if (mounted) {
            context.read<WalletProvider>().refreshWalletData();
          }
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('导入钱包失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isImporting = false;
        });
      }
    }
  }

  /// 从私钥导入
  Future<void> _importFromPrivateKey() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      setState(() {
        _isImporting = true;
      });

      // 从私钥导入钱包，不立即加载余额
      await context.read<WalletProvider>().importWalletFromPrivateKey(
        name: _nameController.text.trim(),
        networkId: _selectedNetwork,
        privateKey: _privateKeyController.text.trim(),
        loadDataImmediately: false, // 加快导入速度
      );

      if (mounted) {
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('✅ 钱包导入成功'),
            backgroundColor: Colors.green,
          ),
        );
        
        // 返回主页后，异步加载钱包数据
        Future.delayed(const Duration(milliseconds: 300), () {
          if (mounted) {
            context.read<WalletProvider>().refreshWalletData();
          }
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('导入钱包失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isImporting = false;
        });
      }
    }
  }
}
